package CreationPattern.Singleton;

import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * @Classname : Vulnerabilities
 * @Description : 以饿汉式为例 解决反射和反序列化破解单例模式漏洞
 * @Author : chentianyu
 * @Date 2022/12/26 23:04
 */


public class Vulnerabilities implements Serializable {
    private static final Vulnerabilities instance = new Vulnerabilities();

    private Vulnerabilities() {
        if (instance != null) {
            // 若通过反射尝试访问私有构造器，则抛出异常
            throw new RuntimeException("警告，正在尝试通过反射的方式直接调用私有构造器！");
        }
    }

    public static Vulnerabilities getInstance() {
        return instance;
    }

    // 反序列化时，如果定义了readResolve()则直接返回此方法指定的对象。而不需要单独再创建新对象！
    private Object readResolve() throws ObjectStreamException {
        return instance;
    }

}
